package cn.itsource.pay.service.impl;

import cn.itsource.basic.constant.AlipayConfig;
import cn.itsource.basic.constant.PayConstants;
import cn.itsource.basic.constant.PethomeConstant;
import cn.itsource.order.domain.ProductOrder;
import cn.itsource.order.mapper.ProductOrderMapper;
import cn.itsource.pay.domain.AlipayInfo;
import cn.itsource.pay.domain.PayBill;
import cn.itsource.pay.mapper.AlipayInfoMapper;
import cn.itsource.pay.mapper.PayBillMapper;
import cn.itsource.pay.service.IPayBillService;
import cn.itsource.quartz.service.IQuartzService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class PayBillServiceImpl implements IPayBillService {

    @Autowired
    private AlipayInfoMapper alipayInfoMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private ProductOrderMapper productOrderMapper;

    @Autowired
    private IQuartzService quartzService;

    @Override
    public String  goBuy(ProductOrder productOrder) {
        try {
            //根据店铺id查询支付信息
            AlipayInfo alipayInfo = alipayInfoMapper.loadByShopid(productOrder.getShop().getId());
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,
                    alipayInfo.getAppid(), alipayInfo.getMerchant_private_key(), "json",
                    AlipayConfig.charset, alipayInfo.getAlipay_public_key(), AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = productOrder.getOrderSn();
            //付款金额，必填
            String total_amount = productOrder.getPrice().toString();
            //订单名称，必填
            String subject = productOrder.getDigest();
            //商品描述，可空
            String body = productOrder.getDigest();

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //请求（就是支付宝返回的 支付界面url地址）
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            return result;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "";


    }

    /**
     *
     * @param out_trade_no 订单编号
     * @param trade_no  支付单的交易号
     */
    @Override
    public void handleState(String out_trade_no, String trade_no) {
        //获取支付单对象
        PayBill payBill = payBillMapper.loadByOrderSn(out_trade_no);
        //设置完成时间
        payBill.setUpdateTime(new Date());
        //支付单交易号
        payBill.setUnionPaySn(trade_no);
        //修改状态
        payBill.setState(PethomeConstant.PAYMENT_COMPLETED);
        //修改支付单对象
        payBillMapper.update(payBill);
        //修改订单状态
        switch (payBill.getBusinessType()){
            //服务
            case PayConstants.BUSINESSTYPE_PRODUCT:
                //获取服务订单
                ProductOrder productOrder = productOrderMapper.loadById(payBill.getBusinessKey());
                productOrder.setState(PethomeConstant.PAYMENT_COMPLETED);
                productOrder.setPaySn(trade_no);
                productOrder.setLastConfirmTime(new Date());
                productOrderMapper.update(productOrder);
                //删除定时器
                quartzService.removeJob(PayConstants.BUSINESSTYPE_PRODUCT + productOrder.getOrderSn());
                break;
             //领养
            case PayConstants.BUSINESSTYPE_ADOPT:
                break;
            //商品
            case PayConstants.BUSINESSTYPE_GOODS:
                break;
        }
    }
}
